package com.bluexmicro.ota2.ui.screen.index

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject

data class VersionInfo(
    val code: Long,
    val name: String
)

class VersionRepository {

    private var client = OkHttpClient()

    companion object {
        const val apiUrl = "https://www.pgyer.com/apiv2/app/view"
        const val appKey = "efa4883273e4b44087aab13149360d09"
        const val apiKey = "cbca0d3c79330ece2e3bf9d7ecdaf9c6"

        const val NAME_API_KEY = "_api_key"
        const val NAME_APP_KEY = "appKey"

        const val appIndexUrl = "https://www.pgyer.com/63O91X"
    }

    suspend fun checkVersion(): VersionInfo? = withContext(Dispatchers.Default) {
        val body = FormBody.Builder()
            .add(NAME_API_KEY, apiKey)
            .add(NAME_APP_KEY, appKey)
            .build()

        val request = Request.Builder()
            .header("Content-Type", "application/x-www-form-urlencoded")
            .url(apiUrl)
            .post(body)
            .build()

        try {
            val response = client.newCall(request).execute()
//            Log.e("TAG", "checkVersion: ${response.body?.string()}")
            val json = JSONObject(response.body!!.string())

            val dataJson = json.getJSONObject("data")
            val versionCode = dataJson.getString("buildVersionNo").toLong()
            val versionName = dataJson.getString("buildVersion")
            VersionInfo(versionCode, versionName)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    fun localVersion(context: Context): VersionInfo {
        return try {
            val packageManager: PackageManager = context.packageManager
            val packageInfo: PackageInfo = packageManager.getPackageInfo(context.packageName, 0)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                VersionInfo(
                    packageInfo.longVersionCode,
                    packageInfo.versionName
                )
            } else {
                VersionInfo(
                    packageInfo.versionCode.toLong(),
                    packageInfo.versionName
                )
            }
        } catch (e: Exception) {
            VersionInfo(
                0,
                "--"
            )
        }

    }

}